package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strings"
	"time"
	"video_-chat/api/request"
	"video_-chat/global"
	"video_-chat/internal/moble"
	"video_-chat/pkg"
)

func VideoListGet(context *gin.Context) {
	var video_list_get request.VideoListGet
	if err := context.ShouldBind(&video_list_get); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201, //100000以上自定义，成功为200，解析失败为100201
			"msg":  err.Error(),
		})
		return
	}
	var video_list []moble.Video
	sql := global.DB.Model(&moble.Video{})
	if video_list_get.Address != "" {
		sql = sql.Where("region_tag like ?", "%"+video_list_get.Address+"%")
	}
	if err := sql.Limit(5).Offset((video_list_get.Page - 1) * 5).Find(&video_list).Error; err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100202,
			"msg":  err.Error(),
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": video_list,
	})
	return
}

func VideoGet(context *gin.Context) {
	var video_get request.VideoGet
	if err := context.ShouldBind(&video_get); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201, //100000以上自定义，成功为200，解析失败为100201
			"msg":  err.Error(),
		})
		return
	}
	var user moble.Users
	var VidLog request.VideoGetLog
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	key := fmt.Sprintf("%d:%d", user.UserId, video_get.Id)
	result, _ := global.RDB.Get(global.Ctx, key).Result()
	if result == "" {
		var video moble.Video
		global.DB.Where("video_id = ?", video_get.Id).Find(&video)
		VidLog.Video = video
		VidLog.Second = 0
		VidLog.Status = "未观看"
	} else {
		json.Unmarshal([]byte(result), &VidLog)
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "开始观看",
		"data": VidLog,
	})
}

func VideoExit(context *gin.Context) {
	var video_exit request.VideoExit
	if err := context.ShouldBind(&video_exit); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201, //100000以上自定义，成功为200，解析失败为100201
			"msg":  err.Error(),
		})
		return
	}
	var user moble.Users
	var VidLog request.VideoGetLog
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	key := fmt.Sprintf("%d:%d", user.UserId, video_exit.Id)
	var video moble.Video
	global.DB.Where("video_id = ?", video_exit.Id).Find(&video)
	VidLog.Video = video
	VidLog.Second = video_exit.Second
	VidLog.Status = fmt.Sprintf("已观看:%.2f%%", (float64(video_exit.Second)/float64(video.Duration))*100)
	set, _ := json.Marshal(VidLog)
	global.RDB.Set(global.Ctx, key, set, 72*time.Hour)
	l_key := fmt.Sprintf("user:%d:lost_video", user.UserId)
	count, _ := global.RDB.LLen(global.Ctx, l_key).Result()
	if count == 10 {
		global.RDB.RPop(global.Ctx, l_key)
	}
	global.RDB.LPush(global.Ctx, l_key, set)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "已记录进度",
		"data": VidLog,
	})
}

func VideoLoginGet(context *gin.Context) {
	var user moble.Users
	var Videos []request.VideoGetLog
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	l_key := fmt.Sprintf("user:%d:lost_video", user.UserId)
	videos, _ := global.RDB.LRange(global.Ctx, l_key, 0, -1).Result()
	for _, video := range videos {
		var Video request.VideoGetLog
		json.Unmarshal([]byte(video), &Video)
		Videos = append(Videos, Video)
	}
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "已追踪上次观看的视频",
		"data": Videos,
	})
}

func VideoCommentPush(context *gin.Context) {
	var video_comment_push request.VideoCommentPush
	if err := context.ShouldBind(&video_comment_push); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201, //100000以上自定义，成功为200，解析失败为100201
			"msg":  err.Error(),
		})
		return
	}
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)

	if strings.Contains(video_comment_push.Data, "http") {
		context.JSON(http.StatusOK, gin.H{
			"code": 100202,
			"msg":  "评论中不可发送链接",
		})
		return
	}

	var Commeng = moble.Comments{
		VideoId:     int32(video_comment_push.VideoId),
		UserId:      user.UserId,
		Content:     video_comment_push.Data,
		CommentTime: time.Now(),
	}

	global.DB.Create(&Commeng)

	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "评论发送成功",
	})

	var Video moble.Video
	global.DB.Where("video_id = ?", video_comment_push.VideoId).Find(&Video)
	rab := pkg.NewRabbitMQSimple(fmt.Sprintf("user:%d", Video.UserId))
	var message moble.Message
	message = moble.Message{
		ReceiverId: Video.UserId,
		SenderId:   user.UserId,
		Type:       1,
		Content:    fmt.Sprintf("用户：%s,给您的视频:%s,留下评论:%s", user.Nickname, Video.Title, Commeng.Content),
		SendTime:   time.Now(),
		IsRead:     0,
	}
	global.DB.Create(&message)
	set, _ := json.Marshal(message)
	rab.PublishSimple(string(set))
}

func VideoCommentGet(context *gin.Context) {
	var video_comment_get request.VideoCommentGet
	if err := context.ShouldBind(&video_comment_get); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201,
			"msg":  err.Error(),
		})
	}
	var comments []moble.Comments
	global.DB.Where("video_id = ?", video_comment_get.Id).Find(&comments)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "评论获取成功",
		"data": comments,
	})
}

func VideoCommentLike(context *gin.Context) {
	var video_comment_like request.VideoCommentLike
	if err := context.ShouldBind(&video_comment_like); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201,
			"msg":  err.Error(),
		})
	}
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	var comment_like moble.CommentLike
	global.DB.Where("comment_id = ? and user_id = ?", video_comment_like.CommentId, user.UserId).Find(&comment_like)
	if comment_like.LikeId != 0 {
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "您已经点过赞了",
		})
		return
	}
	comment_like.CommentId = comment_like.CommentId
	comment_like.UserId = user.UserId
	comment_like.LikeTime = time.Now()
	CommentLike := global.DB.Begin()
	if err := CommentLike.Create(&comment_like).Error; err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100202,
			"msg":  err.Error(),
		})
		CommentLike.Rollback()
		return
	}
	var comment moble.Comments
	CommentLike.Where("comment_id = ? and user_id = ?", comment_like.CommentId, user.UserId).Find(&comment)
	if comment.LikeCount == 0 {
		comment.LikeCount = 1
	} else {
		comment.LikeCount++
	}
	if err := CommentLike.Model(&moble.Comments{}).Where("comment_id = ?", comment_like.CommentId).Updates(&comment).Error; err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100203,
			"msg":  err.Error(),
		})
		CommentLike.Rollback()
		return
	}
	CommentLike.Commit()
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
}

func VideoBarragePush(context *gin.Context) {
	var video_barrage_push request.VideoBarragePush
	if err := context.ShouldBind(&video_barrage_push); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201,
			"msg":  err.Error(),
		})
		return
	}
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	ok := pkg.Baidu(video_barrage_push.Data)
	var bar moble.Barrages
	bar = moble.Barrages{
		UserId:   user.UserId,
		Content:  video_barrage_push.Data,
		SendTime: time.Now(),
		Progress: int32(video_barrage_push.Progress),
		Filtered: 0,
	}
	if ok != "合规" {
		str := bar.Content
		bar.Content = "*******"
		bar.Filtered = 1
		global.DB.Create(&bar)
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "发布失败",
		})
		global.Logger.Info(fmt.Sprintf("用户:%d，不良发言，审核未通过", user.UserId), zap.String(str, ""))

		return
	}
	global.DB.Create(&bar)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}

func VideoBarrageGet(context *gin.Context) {
	var video_barrage_get request.VideoBarrageGet
	if err := context.ShouldBind(&video_barrage_get); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code": 100201,
			"msg":  err.Error(),
		})
		return
	}
	end := video_barrage_get.Progress + 3600
	var bars []moble.Barrages
	global.DB.Where("progress >= ? and progress <= ? and video_id =?", video_barrage_get.Progress, end, video_barrage_get.Id).Find(&bars)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "弹幕加载成功",
		"data": bars,
	})
}
